package com.ahuan.controller;

import com.ahuan.exception.BusinessException;
import com.ahuan.utils.VerifyCodeUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;

/**
 *  @author Ahuan
 *  @date 2023/1/10 15:26
 *  @description 获取图形验证码
 */

@RestController
@RequestMapping("/api")
public class CodeController {
    @GetMapping("/code")
    @ResponseBody
    public void code(HttpServletRequest request, HttpServletResponse response) {
        try {
            //调用工具类生成5位验证码
            String s = VerifyCodeUtil.generateVerifyCode(6);

            //将验证码存入session(也可以设置有效期，这里省略)
            HttpSession session = request.getSession();
            session.setAttribute("codeReal", s);

            //输出图片
            // 禁止图像缓存，session结束时自动失效
            response.setContentType("image/png");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            OutputStream outputStream = response.getOutputStream();
            VerifyCodeUtil.outputImage(750,180,outputStream,s);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("验证码生成失败");
        }
    }
}
